import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class CoffeesExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse<Response>();
    const req = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const excRes = exception.getResponse();

    console.group('coffeesExceptionFilter in');
    console.log('in req', req.url);
    console.log('in res', JSON.stringify(res.getHeaders()));
    console.groupEnd();
    // NOTICE: 堆栈状态是不可枚举的
    // {
    //   stack: {
    //     value: 'BadRequestException: Validation failed\n' +
    //       '    at CusPipe.transform (C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\src\\coffees\\pipes\\cus.pipe.ts:18:13)\n' +
    //       '    at C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\pipes\\pipes-consumer.js:16:33\n' +
    //       '    at processTicksAndRejections (node:internal/process/task_queues:95:5)\n' +
    //       '    at resolveParamValue (C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:147:23)\n' +
    //       '    at async Promise.all (index 0)\n' +
    //       '    at pipesFn (C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:150:13)\n' +
    //       '    at C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:37:30\n' +
    //       '    at C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n' +
    //       '    at C:\\Users\\yhding\\workspace\\gitee\\nest-crash\\node_modules\\.pnpm\\@nestjs+core@9.1.6_bx3wiubfryfbvpzqwr6ml4ajpu\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17',
    //     writable: true,
    //     enumerable: false, // NOTICE: here
    //     configurable: true
    //   },
    // console.log(Object.getOwnPropertyDescriptors(exception));

    res.status(status).json({
      ...(typeof excRes === 'string' ? { message: excRes } : excRes),
      from: 'coffees-exception',
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: req.url,
    });
  }
}
